package other.edan.pass;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.rkhd.platform.sdk.ScheduleJob;
import com.rkhd.platform.sdk.data.model.Department;
import com.rkhd.platform.sdk.data.model.User;
import com.rkhd.platform.sdk.exception.CustomConfigException;
import com.rkhd.platform.sdk.exception.ScriptBusinessException;
import com.rkhd.platform.sdk.exception.XsyHttpException;
import com.rkhd.platform.sdk.log.Logger;
import com.rkhd.platform.sdk.log.LoggerFactory;
import com.rkhd.platform.sdk.param.ScheduleJobParam;
import com.rkhd.platform.sdk.service.CustomConfigService;
import com.rkhd.platform.sdk.service.FutureTaskService;
import com.rkhd.platform.sdk.task.FutureTask;
import other.edan.pass.utils.ComUtils;
import other.edan.pass.utils.DateTools;
import other.edan.pass.utils.HCXObjectService;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName: UserDepartTask
 * Description: 用户离职时，回收基础功能license，使其无法登录系统
 * date: 2024/09/11
 *
 * @author fwm
 */
public class UserDepartTask implements ScheduleJob, FutureTask {
    // 信息配置
    private static Map<String, String> ehrDepartNoticeConfig;           //EHR离职后通知人员 配置信息
    private static final Logger LOGGER = LoggerFactory.getLogger();

    static {
        try {
            CustomConfigService instance = CustomConfigService.instance();

            ehrDepartNoticeConfig = instance.getConfigSet("ehrDepartNotice");
            if (ehrDepartNoticeConfig == null) {
                ehrDepartNoticeConfig = new HashMap<>();
            }

        } catch (CustomConfigException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public void execute(ScheduleJobParam scheduleJobParam) {
        LOGGER.debug("回收用户基础功能license开始");
        try {
            String messageId = FutureTaskService.instance().addFutureTask(UserDepartTask.class, null);
        } catch (Exception e) {
            LOGGER.error("回收用户基础功能license异常, error:", e);
        }
        LOGGER.debug("回收用户基础功能license结束");
    }

    @Override
    public void execute(String s) throws ScriptBusinessException {
        LOGGER.debug("回收用户基础功能license开始");
        try {
            recoveryLicense();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
        }
    }


    //回收用户License
    private  void  recoveryLicense() throws IOException, XsyHttpException {
        //获取两天来更新的用户
        Long twoDaysBefore = DateTools.getDaysBeforeLong(1);
        String sql = "select id,name,ehrUserStatus__c from user " +
                " where (updatedAt >=" + twoDaysBefore +") and (postCode='离职') and (ehrUserStatus__c!=4)";
        List<User> userList = HCXObjectService.queryAll(sql);
        if(userList.size()<=0){
            LOGGER.info("没有离职的用户");
            return;
        }
        LOGGER.info("离职人员数量:"+userList.size()+",离职用户信息:"+userList.toString());

        //取消用户”基础功能license”
        for(User user:userList){
            Long userId=user.getId();

            JSONObject allLicenseJson= ComUtils.getAssignLicenses(userId);
            if(!allLicenseJson.getString("code").equals("0")) {
                LOGGER.info("查询用户已授权的license:失败");
                continue;
            }

            JSONArray records=allLicenseJson.getJSONObject("data").getJSONArray("records");
            if(null==records || records.size()<0) {
                LOGGER.info("查询用户已授权的license:失败");
                continue;
            }

            for(int i=0;i<records.size();i++){
                JSONObject licenseJson=records.getJSONObject(i);
                String licenseName=licenseJson.getString("licenseName");
                if(!licenseName.equals("基础功能")) {
                    continue;
                }

                Long licenseId=licenseJson.getLong("id");
                Boolean result=ComUtils.delLicenseAssignments(userId,licenseId);
                String msg=result?"成功":"失败";
                LOGGER.info("回收用户【"+user.getName()+"】的基础功能License"+msg);
            }
        }

        //更新用户离职状态，并给相关人员发送提醒信息
        for(User updateUser:userList){
            updateUser.setEhrUserStatus__c(4);
            HCXObjectService.update(updateUser);

            //发送提醒信息
            String content=updateUser.getName()+"离职了，请及时处理！";
            JSONObject notice=getNotice(content);
            ComUtils.sendNotification(notice);
        }
    }

    //通知消息
    private JSONObject getNotice(String content){
        JSONObject notice=new JSONObject();
        notice.put("noticeType",0);
        notice.put("content",content);

        JSONArray receivers=new JSONArray();

        //TODO
        String UserIds = ehrDepartNoticeConfig.get("UserIds");
        String[] userIdList=UserIds.split(",");
        for(String userId:userIdList){
            JSONObject receiver=new JSONObject();
            receiver.put("id",Long.parseLong(userId));
            receiver.put("receiverType",0);
            receivers.add(receiver);
        }

        notice.put("receivers",receivers);
        LOGGER.info(notice.toJSONString());

        return  notice;
    }


    public static void main(String[] args) throws IOException, XsyHttpException {
        UserDepartTask api=new UserDepartTask();
        //api.recoveryLicense();

    }
}